<template>
  <div>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="600px" center>
      <!-- title: 标题区的内容 -->
      <!-- footer：底部按钮操作区的内容 -->
      <span slot="title">用户注册</span>

      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="80px"
        label-position="left"
      >
        <!-- 
        action : 上传的地址，跟axios没有关系
        data:上传的时候，需要传递的额外参数，我们现在后台需要传递（他的值是一个对象，对象属性加image。这是后台规定的，值是file类型，也是后台规定的）
        show-file-list:是否展示上传之后的列表
        on-success: 上传成功之后的回调，做两件事，预览 和 给 form.avatar赋值
        on-error: 上传失败的回调，给他一个提示
        before-upload: 上传之前的回调，可以在这里检测文件类型和大小，还可以给额外参数赋值
       -->
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :before-upload="beforeAvatarUpload"
            :data="uploadData"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password"></el-input>
        </el-form-item>

        <el-row>
          <el-col :span="16">
            <el-form-item label="图形码" prop="code">
              <el-input
                v-model="form.code"
                placeholder="请输入图形码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col style="margin-left: 10px" :span="7">
            <!-- 注册时候的验证码，跟登录的时候不一样 -->
            <img
              :src="RegisterCodeURL"
              style="width: 100%; height: 40px"
              @click="changeRegisterCodeURL"
            />
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16">
            <el-form-item label="验证码" prop="rcode">
              <el-input
                v-model="form.rcode"
                placeholder="请输入验证码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col style="margin-left: 10px" :span="7">
            <el-button size="default" @click="getRcode"
              >获取用户验证码</el-button
            >
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="register"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      
      dialogVisible: false,
      RegisterCodeURL: `${process.env.VUE_APP_BASEURL}/captcha?type=sendsms`,
      // 上传相关
      imageUrl: "", // 上传之后的图像地址
      uploadUrl: `${process.env.VUE_APP_BASEURL}/uploads`, // 上传的地址
      uploadData: {
        // 上传时候的额外的参数
        image: null
      },

      form: {
        avatar: "", // 头像地址
        username: "", // 昵称
        email: "", // 邮箱
        phone: "", // 手机号
        password: "", // 密码
        code: "", // 图形码
        rcode: "", // 验证码
      },
      rules: {
        avatar: [
          { required: true, message: "头像不能为空", trigger: "change" },
        ],
        username: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              // rule:校验规则   value:用户输入的值， callback：校验的结果，无论成功与否都需要调用
              if (!value) {
                return callback(new Error("邮箱不能为空"));
              }

              // 利用邮箱的正则去进行匹配
              // eslint禁用
              /* eslint-disable */
              let myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
              // eslint启用
              /* eslint-enable */
              if (!myreg.test(value)) {
                return callback(new Error("邮箱不合法"));
              }

              callback();
            },
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error("手机号不能为空"));
              }

              // 手机的正则校验
              // eslint禁用
              /* eslint-disable */
              let reg = /^1(3[0-9]|4[5,7]|5[0,1,2,3,5,6,7,8,9]|6[2,5,6,7]|7[0,1,7,8]|8[0-9]|9[1,8,9])\d{8}$/;
              // eslint启用
              /* eslint-enable */
              if (!reg.test(value)) {
                return callback(new Error("手机号不合法"));
              }
              callback();
            },
            trigger: "blur", // 触发时机
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur",
          },
          { min: 6, max: 16, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        code: [
          {
            required: true,
            message: "图形码不能为空",
            trigger: "blur",
          },
        ],
        rcode: [
          {
            required: true,
            message: "验证码不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },

  methods: {
    // 重新获取图像验证码
    changeRegisterCodeURL() {
      this.RegisterCodeURL = `${
        process.env.VUE_APP_BASEURL
      }/captcha?type=sendsms$t=${new Date() - 0}`;
    },
    async getRcode() {
      // 判断用户是否输入了手机号和图形验证码
      // 校验部分字段
      let isOK = 0;
      this.$refs.form.validateField(["phone"], (errorMessage) => {
        if (!errorMessage) {
          isOK++;
        }
      });
      this.$refs.form.validateField(["code"], (errorMessage) => {
        if (!errorMessage) {
          isOK++;
        }
      });

      if (isOK === 2) {
        const res = await this.$axios.post("/sendsms", {
          phone: this.form.phone,
          code: this.form.code,
        });
        if (res.code == 200) {
          this.form.rcode = res.data.captcha;
        } else {
          // 注册失败就刷新一下验证码
          this.changeRegisterCodeURL();
          // 提示一下错误信息
          this.$message.error(res.message);
        }
      }
    },

    // 上传相关的方法
    // 上传成功之后
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        // 实现预览
        this.imageUrl = URL.createObjectURL(file.raw);
        // 赋值给form.avatar，因为上传成功要把 avatar 传给后台
        this.form.avatar = res.data.file_path;
      } else {
        this.$message.error(res.message);
      }
    },
    // 上传失败
    handleAvatarError(err) {
      console.log(err);
      this.$message.error("上传失败");
    },
    // 上传之前
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png" || file.type ==="image/gif";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/png/gif 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      // 给需要传递的额外参数赋值
      this.uploadData.image = file;
      return isJPG && isLt2M;
    },
    // 注册
    register(){
      this.$refs.form.validate(async valid=>{
        if(!valid) return

        delete this.form.code
        // 发送axios
        const res = await this.$axios.post('/register',this.form)
        if(res.code === 200){
          this.$message.success('注册成功')
          this.dialogVisible == false
        }else{
          this.$message.error('注册失败')
          this.changeRegisterCodeURL()
        }
      })
    }
  },
  // 侦听器
  watch: {
    dialogVisible(newValue){
      if(!newValue){
        this.$refs.form.resetFields()
        this.imageUrl=""
      }
    }
  },
};
</script>

<style>

.avatar-uploader {
  display: flex;
  justify-content: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>